<?php
namespace Admin\Model;
class NodeModel extends \Think\Model{

    //表名
    public $tableName = 'node';
    public $accessTable = 'access';

    //表单验证
    protected $_validate = array(
        array('title', 'require', '名称不能为空'),
        array('module', 'require', '模块不能为空'),
        //array('controller', 'require', '控制器不能为空'),
        //array('action', 'require', '动作不能为空'),
    );

    //添加节点
    public function addNode()
    {
        if ($this->create()) {
            if ($this->add()) {
                return true;
            } else {
                $this->error = '添加失败';
            }
        }
    }

    //修改节点
    public function editNode()
    {
        if ($this->create()) {
            if (false !== $this->save()) {
                return true;
            } else {
                $this->error = '操作失败';
            }
        }
    }

    //删除节点
    public function delNode()
    {
        $nid = I("nid", 0, 'intval');
        if (!$nid) {
            $this->error = '参数错误';
            return false;
        }
        $state = $this->where(array("pid" => $nid))->find();
        if ($state) {
            $this->error = '请删除子菜单';
            return false;
        }
        if ($this->delete($nid)) {
            $map['nid'] = $nid;
            M($this->accessTable)->where($map)->delete();
            return true;
        } else {
            $this->error = '删除失败';
        }
    }

    //获取菜单缓存
    public function getMenu()
    {
        $data = $this->select();
        if (empty($data)) {
            return false;
        }
        $cache = S('NodeMenu');
        if(!$cache) {
            $cache = $this->refreshMenuCache();
        }
        return $cache;
    }

    //刷新菜单缓存
    public function refreshMenuCache()
    {
        $data = $this->select();
        if (empty($data)) {
            return false;
        }
        $cache = array();
        foreach ($data as $rs) {
            $cache[$rs['id']] = $rs;
        }
        S('NodeMenu', $cache);
        return $cache;
    }

    //获取所有普通菜单ID
    public function getMenuIds()
    {
        $ids = array();
        $list = M($this->tableName)->field('nid')->where(array('type'=>2))->select();
        foreach($list as $r) {
            $ids[] = $r['nid'];
        }
        return $ids;
    }

    //获取子孙节点id
    public function sonIds($pid)
    {
        static $ids;
        $list = $this->field('nid')->where(array("pid" => $pid))->select();
        if($list) {
            foreach ($list as $r) {
                $ids[] = $r['nid'];
                $this->sonIds($r['nid']);
            }
        }
        return $ids ? $ids : array();
    }
}